#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：Employment_class 
@File    ：02_显示需要显示的页面.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/7/007 10:13 
"""

import re
import socket
from multiprocessing import Process

documentRoot = './html/index.html'


def handleClient(ClientSocket):
    global responseHeaderLines, responseBody
    recvData = ClientSocket.recv(2014)
    requestHeaderLines = recvData.splitlines()
    for line in requestHeaderLines:
        print(line)

    # httpRequestMethodLine = requestHeaderLines[0]
    # getFileName = re.match("[^/]+(/[^ ]*)", httpRequestMethodLine).group(1)
    # print("file name is _____>%s" % getFileName)
    # if getFileName == "/":
    #     getFileName = "/index.html"
    # else:
    #     getFileName = getFileName
    # print("file name is _____2>%s" % getFileName)

    try:
        f = open(documentRoot, "r", encoding="utf-8")
        print("文件名称：", documentRoot)
    except Exception:
        responseHeaderLines = "HTTP/1.1 404 not found\r\n"
        responseHeaderLines += "\r\n"
        responseBody = "====sorry ,file not found===="
    else:
        responseHeaderLines = "HTTP/1.1 200 OK\r\n"
        responseHeaderLines += "\r\n"
        responseBody = f.read()
        f.close()
    finally:
        response = responseHeaderLines + responseBody
        ClientSocket.send(response.encode("utf-8"))
        ClientSocket.close()


def main():
    '作为程序的主控制入口'

    serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serverSocket.bind(("", 7789))
    serverSocket.listen(10)
    while True:
        clientSocket, clientAddr = serverSocket.accept()
        clientP = Process(target=handleClient, args=(clientSocket,))
        clientP.start()
        clientSocket.close()


if __name__ == '__main__':
    # print(b'Postman-Token: 15731f99-fad3-4120-bd3a-a48957a44638'.splitlines())
    # with open(documentRoot, "r") as fp:
    #     print(fp.read())
    main()